import { useAPIUtils } from "@/components/APIUtilsProvider";
import { WithwingsDropzone } from "@/components/WithwingsDropzone";
import {
  Box,
  Button,
  Fieldset,
  Grid,
  Group,
  Modal,
  MultiSelect,
  NumberInput,
  Textarea,
  TextInput,
} from "@mantine/core";
import { useForm } from "@mantine/form";

export function ProductEdit({ source, opened, setOpened }) {
  const form = useForm({
    initialValues: source
      ? {
          ...source,
          originalPrice: source.meta.originalPrice,
          imageUrl: source.meta.imageUrl,
          weight: source.meta.weight,
          detailImageUrl: source.meta.detailImageUrl,
          categories: source.meta.categories,
          treatmentEffect: source.meta.treatmentEffect,
        }
      : {
          pv: 0,
          price: 0,
          originalPrice: 0,
          name: "",
          weight: 0,
          description: "",
          categories: [],
          treatmentEffect: "",
          feedback: "",
        },

    validate: {
      name: (value) =>
        /^[^\s]+$/.test(value) ? null : "请填写商品名，不能包含空格等特殊字符",
      weight: (value) =>
        /^(?:[1-9]?\d{1,3}|9999)$/.test(value) ? null : "权重为0至9999间数字",
      treatmentEffect: (value) =>
        /^[^\s]+$/.test(value)
          ? null
          : "请填写用途功效，不能包含空格等特殊字符",

      description: (value) => (/\S/.test(value) ? null : "请填写商品描述"),
    },
  });

  const { restPOST, restPUT, tanstackInvalidate, tanstackQuery } =
    useAPIUtils();

  const modifyProduct = async (values) => {
    await restPUT(`/api/admin/products/${source.id}`, values);
    tanstackInvalidate(`/api/admin/products`);
    tanstackInvalidate(`/api/products/${source.id}`);
    setOpened(false);
  };

  const createProduct = async (values) => {
    await restPOST(`/api/admin/products`, values);
    tanstackInvalidate(`/api/admin/products`);
    form.reset();
    setOpened(false);
  };

  const categoryQuery = tanstackQuery(`/api/dictionaries/product_category`);

  const categories = categoryQuery.data
    ? Object.entries(categoryQuery.data).map(([key, value]) => ({
        label: `${value.text}(${key})`,
        value: key,
      }))
    : [];

  return (
    <>
      <Modal
        size={"80%"}
        opened={opened}
        onClose={() => {
          setOpened(false);
          form.reset();
        }}
        title={source ? "编辑商品" : "新增商品"}
      >
        <Box w="96%" mx="auto">
          <form
            onSubmit={
              source
                ? form.onSubmit(modifyProduct)
                : form.onSubmit(createProduct)
            }
          >
            <Grid>
              <Grid.Col span={8}>
                <TextInput
                  withAsterisk
                  label="商品名"
                  {...form.getInputProps("name")}
                />
                <MultiSelect
                  clearable
                  label="商品分类"
                  data={categories}
                  {...form.getInputProps("categories")}
                />

                <NumberInput
                  withAsterisk
                  label="单价"
                  min={0} // 限制最小值为 0
                  step={1} // 每次增加或减少为 0.01（允许小数）
                  precision={2} // 小数点后保留 2 位
                  {...form.getInputProps("price")}
                />
                <NumberInput
                  label="原价"
                  min={0} // 限制最小值为 0
                  step={1} // 每次增加或减少为 0.01（允许小数）
                  precision={2} // 小数点后保留 2 位
                  {...form.getInputProps("originalPrice")}
                />
                <NumberInput
                  withAsterisk
                  label="积分"
                  min={0} // 限制最小值为 0
                  step={1} // 每次增加或减少为 0.01（允许小数）
                  precision={2} // 小数点后保留 2 位
                  {...form.getInputProps("pv")}
                />
                <NumberInput
                  withAsterisk
                  label="权重"
                  min={0}
                  max={9999}
                  allowDecimal={false}
                  step={1}
                  precision={0}
                  {...form.getInputProps("weight")}
                />
                <TextInput
                  label="用途功效"
                  {...form.getInputProps("treatmentEffect")}
                />
                <TextInput
                  label="用户反馈"
                  {...form.getInputProps("feedback")}
                />
                {!source && (
                  <NumberInput
                    withAsterisk
                    label="初始库存"
                    min={1} // 限制最小值为 1
                    step={1} // 每次增加或减少为 1
                    precision={0} // 精度为 0，确保只能输入整数
                    {...form.getInputProps("stock")}
                  />
                )}
                <Textarea
                  autosize
                  withAsterisk
                  minRows={6}
                  label="商品描述"
                  {...form.getInputProps("description")}
                />
              </Grid.Col>
              <Grid.Col span={4}>
                <Fieldset legend="商品图片">
                  <WithwingsDropzone
                    src={form.values.imageUrl}
                    text={"点击更换主图"}
                    onSuccess={(url) => {
                      form.setFieldValue("imageUrl", url);
                    }}
                  />
                  <WithwingsDropzone
                    src={form.values.detailImageUrl}
                    text={"点击更换详情图"}
                    onSuccess={(url) => {
                      form.setFieldValue("detailImageUrl", url);
                    }}
                  />
                </Fieldset>
              </Grid.Col>
            </Grid>

            <Group justify="flex-end" mt="md">
              <Button type="submit">提交</Button>
            </Group>
          </form>
        </Box>
      </Modal>
    </>
  );
}
